import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * User: ttq
 * Date: 13-7-5
 * Time: 下午2:33
 * To change this template use File | Settings | File Templates.
 */
public class OutputReplaceFilter implements Filter {
    private Properties properties = new Properties();

    public void init(FilterConfig config) throws ServletException {
        String file = config.getInitParameter("file");
        String realPath = config.getServletContext().getRealPath(file);
        try {
            properties.load(new FileInputStream(realPath));
        } catch (IOException e) {
        }
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpCharacterResponseWrapper responseWrapper = new HttpCharacterResponseWrapper((HttpServletResponse) response);
        chain.doFilter(request, response);
        String output = responseWrapper.getCharArrayWriter().toString();
        for (Object obj : properties.keySet()) {
            String key = (String) obj;
            output = output.replace(key, properties.getProperty(key));
        }

        PrintWriter printWriter = response.getWriter();
        printWriter.write(output);
        printWriter.println("");
    }

    public void destroy() {
    }
}
